<template>
  <div>
    <p-table
      class="table-list-container"
      :row-key="(record, index) => index"
      :pagination="false"
      :columns="columns"
      bordered
      :data-source="totalData"
    />
  </div>
</template>

<script>
import { isObject } from '@/utils/is';
import _ from 'lodash';
import Decimal from 'decimal.js';
let idKey = 0;
export default {
  props: {
    dataSource: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {};
  },
  computed: {
    totalKeys() {
      // const defaultKeys = this.dataSource[1]?.monthSupplyDemands || [];
      const dataSource = JSON.parse(JSON.stringify(this.dataSource));
      let defaultKeys = [];
      dataSource.forEach((item) => {
        if (item.monthSupplyDemands.length > defaultKeys.length) {
          defaultKeys = item.monthSupplyDemands;
        }
      });
      const obj = defaultKeys.reduce((pre, cur) => {
        pre[`${cur.month}.demand`] = '';
        pre[`${cur.month}.supply`] = '';
        pre[`${cur.month}.difference`] = '';
        return pre;
      }, {});

      return Object.keys(obj);
    },
    formatList() {
      if (!this.dataSource.length) return [];
      return this.dataSource.map((item) => {
        const months = item.monthSupplyDemands?.reduce((pre, cur) => {
          pre[cur.month] = cur.supplyDemand;
          return pre;
        }, {});
        return {
          id: ++idKey,
          application: item.application,
          customerName: item.customerName,
          ...months,
        };
      });
    },
    groups() {
      return this.formatList.reduce((pre, cur) => {
        if (pre[cur.customerName]) {
          pre[cur.customerName].push(cur);
        } else {
          pre[cur.customerName] = [cur];
        }
        return pre;
      }, {});
    },
    totalIndex() {
      return this.totalData.reduce((pre, cur, index) => {
        if (cur.id === 'totalKey') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    totalData() {
      if (!this.formatList.length) {
        return [];
      }

      const totalAll = this.formatList.reduce(
        (pre, cur) => {
          this.totalKeys.forEach((key) => {
            if (!_.get(pre, key)) {
              _.set(pre, key, 0);
            }
            const tempValue = new Decimal(_.get(pre, key)).plus(
              new Decimal(_.get(cur, key) || 0)
            );
            if (key.startsWith('price')) {
              _.set(pre, key, tempValue.toFixed(2));
            } else {
              _.set(pre, key, tempValue.toFixed());
            }
          });
          // pre.application = cur.application;
          // pre.customerName = cur.customerName;
          return pre;
        },
        { id: 'totalKeyAll', application: '总计' }
      );

      return [...this.formatList, totalAll];
    },
    columns() {
      if (!this.dataSource.length) return [];
      const dataSource = JSON.parse(JSON.stringify(this.dataSource));
      const titleObj = {
        application: '应用别',
        demand: '需求',
        supply: '供应',
        difference: '供需差异',
      };
      let defaultObj = {};
      let defaultKeys = [];
      dataSource.forEach((item) => {
        if (item.monthSupplyDemands.length > defaultKeys.length) {
          defaultKeys = item.monthSupplyDemands;
          defaultObj = item;
        }
      });
      // let array = [];
      // dataSource.forEach((item) => {
      //   if (item.monthSupplyDemands.length !== 0) {
      //     item.monthSupplyDemands.forEach((el) => {
      //       if (Object.keys(el.data).length > array.length) {
      //         array = Object.keys(el.data);
      //         defaultObj.m3ApplicationData.forEach((it) => {
      //           it.data = el.data;
      //         });
      //       }
      //     });
      //   }
      // });
      const defaultObjKeys = this.delOne(
        'customerName',
        Object.keys(defaultObj)
      );

      const columns = defaultObjKeys.map((item) => {
        const value = defaultObj[item];
        if (isObject(value)) {
          return value.map((month) => {
            const column = {
              align: 'center',
              title: month.month,
              children: Object.keys(month.supplyDemand).map((el) => {
                return {
                  align: 'center',
                  title: titleObj[el],
                  dataIndex: `${month.month}.${el}`,
                };
              }),
            };
            return column;
          });
        }
        const title = titleObj[item];
        return {
          align: 'center',
          title,
          dataIndex: item,
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, item);
          },
        };
      });
      return columns.flat(Infinity);
    },
  },

  watch: {},
  created() {},
  mounted() {},
  methods: {
    delOne(str, arr) {
      const index = arr.indexOf(str);
      arr.splice(index, 1);
      return arr;
    },
    customRender(children, index, row, key) {
      const attrs = {};
      if (key === 'customerName') {
        const data = this.groups[row.customerName] || [];
        if (row.id === data[0]?.id) {
          attrs.rowSpan = data.length + 1;
        } else if (row.id === 'totalKeyAll') {
          console.log('row.id: ', row.id);
          attrs.rowSpan = 1;
          attrs.colSpan = 2;
        } else {
          attrs.rowSpan = 0;
        }
      }
      // if (key === 'application' && row.id === 'totalKeyAll') {
      //   attrs.colSpan = 0;
      // }
      return {
        children,
        attrs,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.table-list-container {
  margin-top: 20px;
}
</style>
